﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;


namespace Common
{
    /// <summary>
    ///JsonConvert 的摘要说明
    /// </summary>
    public class JsonConvert
    {
        public JsonConvert()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //            
        }
         public static string GetAjaxString(DataTable DataSource,Hashtable OutPutParams)
         {
                          
             string strItemCollection = "";
             for (int i = 0; i < DataSource.Rows.Count; i++)
             {
                 string strItemContent = "";
                 foreach (DictionaryEntry item in OutPutParams)
                 {
                     if (strItemContent == "")
                     {
                         strItemContent += "'{0}':'{1}'";
                     }
                     else
                     {
                         strItemContent += ",'{0}':'{1}'";
                     }
                     strItemContent = string.Format(strItemContent, item.Key, DataSource.Rows[i][item.Value.ToString()].ToString());
                 }
                 if (strItemCollection == "")
                 {
                     strItemCollection += "{" + strItemContent + "}";
                 }
                 else
                 {
                     strItemCollection += ",{" + strItemContent + "}";
                 }
             }


             return "{'Items':[" + strItemCollection + "]} ";
         }

         public static List<T> JSONStringToList<T>(string JsonStr)
         {
             JavaScriptSerializer serializer = new JavaScriptSerializer();
             return serializer.Deserialize<List<T>>(JsonStr);
         }



         /// <summary>
         /// 序列化方法（带分页）
         /// </summary>
         /// <param name="dt"></param>
         /// <returns></returns>
         public static string SerializeP(DataTable dt, int count)
         {
             List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
             foreach (DataRow dr in dt.Rows)
             {
                 Dictionary<string, object> result = new Dictionary<string, object>();
                 foreach (DataColumn dc in dt.Columns)
                 {
                     if (dc.DataType == System.Type.GetType("System.DateTime"))
                     {
                         result.Add(dc.ColumnName, dr[dc].ToString() == "" ? "" : Convert.ToDateTime(dr[dc].ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
                     }
                     else
                     {
                         result.Add(dc.ColumnName, dr[dc].ToString());
                     }
                 }
                 list.Add(result);
             }
             string strReturn = "";
             if (count == 0)
             {
                 strReturn = "{\"total\":0,\"rows\":[]}";
             }
             else
             {
                 strReturn = static_ConventToJson(list, count);
             }
             return strReturn;
         }
         /// <summary>
         /// 序列化方法（带分页）
         /// </summary>
         /// <param name="dt"></param>
         /// <returns></returns>
         public static string static_SerializeP(DataTable dt, int count)
         {
             List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
             foreach (DataRow dr in dt.Rows)
             {
                 Dictionary<string, object> result = new Dictionary<string, object>();
                 foreach (DataColumn dc in dt.Columns)
                 {
                     if (dc.DataType == System.Type.GetType("System.DateTime"))
                     {
                         result.Add(dc.ColumnName, dr[dc].ToString() == "" ? "" : Convert.ToDateTime(dr[dc].ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
                     }
                     else
                     {
                         result.Add(dc.ColumnName, dr[dc].ToString());
                     }
                 }
                 list.Add(result);
             }
             string strReturn = "";
             if (count == 0)
             {
                 strReturn = "{\"total\":0,\"rows\":[]}";
             }
             else
             {
                 strReturn = static_ConventToJson(list, count);
             }
             return strReturn;
         }
         /// <summary>
         /// 转换为JSON对象
         /// </summary>
         /// <returns></returns>
         public static string static_ConventToJson<T>(List<T> list, int count)
         {
             JavaScriptSerializer serializer = new JavaScriptSerializer();
             string strJson = serializer.Serialize(list);
             strJson = strJson.Substring(1);
             strJson = strJson.Insert(0, "{\"total\":" + count + ",\"rows\":[");
             strJson += "}";

             return strJson;
         }

         /// <summary>
         /// 序列化方法不需要分页
         /// </summary>
         /// <param name="dt"></param>
         /// <returns></returns>
         public static string Serialize(DataTable dt)
         {
             JavaScriptSerializer serializer = new JavaScriptSerializer();
             List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
             foreach (DataRow dr in dt.Rows)
             {
                 Dictionary<string, object> result = new Dictionary<string, object>();
                 foreach (DataColumn dc in dt.Columns)
                 {
                     if (dc.DataType == System.Type.GetType("System.DateTime"))
                     {
                         result.Add(dc.ColumnName, dr[dc].ToString() == "" ? "" : Convert.ToDateTime(dr[dc].ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
                     }
                     else
                     {
                         result.Add(dc.ColumnName, dr[dc].ToString());
                     }

                 }
                 list.Add(result);
             }
             return serializer.Serialize(list); ;
         }
         /// <summary>
         /// json反序列化为list对象
         /// </summary>
         /// <typeparam name="T"></typeparam>
         /// <param name="jsonString"></param>
         /// <returns></returns>
         public static T JsonDeserialize<T>(string jsonString)
         {
             DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
             MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
             T obj = (T)ser.ReadObject(ms);
             return obj;
         }

         /// <summary>
         ///格式化json格式 返回json
         /// </summary>
         /// <param name="dt"></param>
         /// <returns></returns>
         public static string returnstrjson(DataTable dt)
         {
             string strJson = Serialize(dt);
             strJson = strJson.Substring(1);
             strJson = strJson.Insert(0, "{\"Success\":1,\"ResultText\":\"\",\"Total\":" + dt.Rows.Count + ",\"Items\":[");
             strJson += "}";
             return strJson;
         }

        /// <summary>
        /// 将dt转化成Json数据 格式如 table[{id:1,title:'体育'},id:2,title:'娱乐'}]
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string DtToSON(DataTable dt)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("recordcount:" + dt.Rows.Count + ",table: [");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (i > 0)
                    jsonBuilder.Append(",");
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (j > 0)
                        jsonBuilder.Append(",");
                    jsonBuilder.Append(dt.Columns[j].ColumnName.ToLower() + ": '" + dt.Rows[i][j].ToString().Replace("\t", " ").Replace("\r", " ").Replace("\n", " ").Replace("\'", "\\\'") + "'");
                }
                jsonBuilder.Append("}");
            }
            jsonBuilder.Append("]");
            return jsonBuilder.ToString();
        }

        #region dataTable转换成Json格式
        /// <summary>  
        /// dataTable转换成Json格式  
        /// </summary>  
        /// <param name="dt"></param>  
        /// <returns></returns>  
        public static string DataTable2Json(DataTable dt)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(dt.Columns[j].ColumnName);
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(dt.Rows[i][j].ToString());
                    jsonBuilder.Append("\",");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("},");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            return jsonBuilder.ToString();
        }

        #endregion dataTable转换成Json格式

        public static string DatatableSerialize(DataTable dt)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            foreach (DataRow row in dt.Rows)
            {
                Dictionary<string, object> item = new Dictionary<string, object>();
                foreach (DataColumn column in dt.Columns)
                {
                    if (column.DataType == Type.GetType("System.DateTime"))
                    {
                        item.Add(column.ColumnName, (row[column].ToString() == "") ? "" : Convert.ToDateTime(row[column].ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
                    }
                    else
                    {
                        item.Add(column.ColumnName, row[column]);
                    }
                }
                list.Add(item);
            }
            return serializer.Serialize(list);
        }


    }
   
}
